import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home'
import { isLogin } from '@utils'
Vue.use(VueRouter)
// 定义路由
const routes = [
  {
    path: '/home',
    name: '首页',
    component: Home,
    meta: {
      needLogin: false
    }
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('@views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: true
    }
  },
  { // 动他路由传参
    path: '/itemList/:cateId',
    name: '商品列表',
    component: () => import('@views/ItemList'),
    meta: {
      needLogin: false
    }
  },
  {
    // query 传参
    path: '/detail',
    name: '商品列表',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: '登录页',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/contactLists',
    name: '联系人列表',
    component: () => import('@views/ContactLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/oder',
    name: '订单页',
    component: () => import('@views/Oder'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contacadd',
    name: '新增联系人',
    component: () => import('@views/ContacAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contacEsit',
    name: '编辑联系人',
    component: () => import('@views/ContacEsit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: '搜索页',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResult',
    name: '搜索页结果页',
    component: () => import('@views/SearchResult'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 判断当前路由是否需要登录
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 登录了
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要登录
    next()
  }
})
export default router
